package android.androidapp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class Startup extends MapActivity {
	
	  private LocationManager lm;
	  private LocationListener locationListener;
	  private MapView mapView;
	  private MapController mc;
	  private LocationInfo[] locationObjects;
	  
	  public CustomBalloonItemizedOverlay itemizedOverlayNear;
	  public CustomBalloonItemizedOverlay itemizedOverlayFar;
	  public CustomItemizedOverlay itemizedOverlayCurrent;
	  
	  private int closestPoints = 5;
	  private double longStart = -81.20020866394043;
	  private double latStart = 28.602307294076848;
	
	  // Called when the activity is first created.
	  @Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main); 
	    
	    try
	    {
		    //SETUP MAP
		    mapView = (MapView) findViewById(R.id.mapview1);
		    mapView.setBuiltInZoomControls(true);
		    mc = mapView.getController();
		    
		    // GPS LOCATION MANAGER
		    lm = (LocationManager) 
		    getSystemService(Context.LOCATION_SERVICE);            
		    locationListener = new MyLocationListener(mc,mapView,this);      
		    lm.requestLocationUpdates(
		    LocationManager.GPS_PROVIDER, 1000, 100, locationListener);
		    
		    //Middle of UCF. Start position.
		    double longitudeStart = longStart * 1E6;
		    double latitudeStart = latStart * 1E6;
		    
		    //Try to get last GPS cords. 
		    try
		    {
		    	longitudeStart = lm.getLastKnownLocation(
		                LocationManager.GPS_PROVIDER)
		                .getLongitude()* 1E6;
		    	latitudeStart = lm.getLastKnownLocation(
		                LocationManager.GPS_PROVIDER)
		                .getLatitude()* 1E6;
		    	
		    	//Do check for out of bounds. 
		    }
		    catch(Exception e)
		    {
		    	Log.e("ERROR", e.toString());
		    }
		    
		    //Zoom to UCF location at first or gps position
		    GeoPoint point = new GeoPoint(
	                ((int) (latitudeStart)), 
	                ((int) (longitudeStart)));
	        mc.animateTo(point);
	        mc.setZoom(17);                
	        mapView.invalidate();
	        
	        //Get phone number, send account data, get account data
	        TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
	        String phoneNumber = telephonyManager.getLine1Number();
	        
		    //Set current location
	        if(this.itemizedOverlayCurrent == null)
	        {
			    Drawable drawableNear = this.getResources().getDrawable(R.drawable.map_pin_target);
			    this.itemizedOverlayCurrent = new CustomItemizedOverlay(drawableNear,mapView);
	        }
	        
	        //Update current position on map with point
		    OverlayItem overlayitemCurrent = new OverlayItem(point, "ME!", "ME!");
		    this.itemizedOverlayCurrent.addOverlay(overlayitemCurrent);
		    
		    //Get map points and update them on the map
		    locationObjects = JsonClient.getLocationObjects();
		    this.updateOverlayWithClosestPoints(latitudeStart, longitudeStart);
		    
		    //Add the overlays (for everything)
		    List<Overlay> mapOverlays = mapView.getOverlays();
		    mapOverlays.add(itemizedOverlayCurrent);
		    mapOverlays.add(itemizedOverlayNear);
		    mapOverlays.add(itemizedOverlayFar);
		    
	    }
	    catch(Exception e)
	    {
	    	Log.e("ERROR",e.toString());
	    }

	  }

	  @Override
	  protected boolean isRouteDisplayed() {
	    return false;
	  } 
	  
	  public void updateOverlayWithClosestPoints(Double currentLocationLat, Double currentLocationLong)
	  {    
		    //Drawable icons
		    Drawable drawableNear = this.getResources().getDrawable(R.drawable.grn_pushpin);
		    Drawable drawableFar = this.getResources().getDrawable(R.drawable.wht_pushpin);
		    
		    if(itemizedOverlayNear == null)
		    	itemizedOverlayNear = new CustomBalloonItemizedOverlay(drawableNear,mapView);
		    
		    if(itemizedOverlayFar == null)
		    	itemizedOverlayFar = new CustomBalloonItemizedOverlay(drawableFar,mapView);
		    
		  if(locationObjects !=null)
		  {

		    //Loop to update distance from current GPS point and refresh list to be sorted.
		    for(int i = 0; i < locationObjects.length;i++)
		    {
		    	locationObjects[i].updateDistance(currentLocationLat, currentLocationLong);
		    }
		    
		    if(locationObjects.length > 0)
		    	Arrays.sort(locationObjects); //sort
		    
		    int[] eventPoiIDs = JsonClient.getCurrentEventInformationPOIIDs();
		    
		    //Loop to add all closest event points
		    itemizedOverlayNear.clearOverlay();
		    for(int i = 0; i < locationObjects.length;i++)
		    {
		    	if(i < closestPoints)
		    	{
		    		if(ContainsIDInArray(eventPoiIDs,locationObjects[i].id))
		    		{
				    	int latitude = locationObjects[i].latitude.intValue();
				    	int longitude = locationObjects[i].longitude.intValue();
				    	
					    GeoPoint pointNear = new GeoPoint(
				                latitude, 
				                longitude);
					    
					    OverlayItem overlayitemNear = new OverlayItem(pointNear, locationObjects[i].name, Integer.toString(locationObjects[i].id));
					    itemizedOverlayNear.addOverlay(overlayitemNear);
		    		}
		    	}
		    }
		    
		    
		    //Loop to add all closest non-event points
		      itemizedOverlayFar.clearOverlay();
		    for(int i = 0; i < locationObjects.length;i++)
		    {
		    	if(i < closestPoints)
		    	{
		    		if(!ContainsIDInArray(eventPoiIDs,locationObjects[i].id))
		    		{
				    	int latitude = locationObjects[i].latitude.intValue();
				    	int longitude = locationObjects[i].longitude.intValue();
				    	
					    GeoPoint pointFar = new GeoPoint(
				                latitude, 
				                longitude);
					    
					    OverlayItem overlayitemFar = new OverlayItem(pointFar, locationObjects[i].name, Integer.toString(locationObjects[i].id));
					    itemizedOverlayFar.addOverlay(overlayitemFar);
		    		}
		    	}
		    }
		    
		    
		    mapView.postInvalidate();

		  }
	  }
	  
	  private boolean ContainsIDInArray(int[] inputArray, int value)
	  {
		  boolean result = false;
		  
		  if(inputArray == null || inputArray.length == 0)
		  {
			  return result;
		  }
		  
		  for(int i = 0; i < inputArray.length;i++)
		  {
			  if(inputArray[i] == value)
			  {
				  result = true;
				  break;
			  }
		  }
		  
		  return result;
	  }
	  
}